from fastapi import Request
from pydantic import BaseModel
from tortoise.transactions import atomic, in_transaction

from models.user import User
from service import UserService
from common.result.Result import Result
from common.enum import BaseEnum
from common.const import BaseConstant
from util.log import Log
from util.token import Token
from util.time import Time
from util.str import Str
from util.redis import Redis

class body(BaseModel):
    username: str
    password: str
    confirmPassword: str

async def Register(req: Request, body: dict):
    try:
        async with in_transaction() as connection:
            # 参数校验
            username = body.get('username')
            password = body.get('password')
            confirmPassword = body.get('confirmPassword')
            if Str.isBlank(username, password, confirmPassword):
                Log.error('参数为空，检查参数')
                return Result.error(BaseEnum.PARAMETER_INVALID_ERROR)

            if password != confirmPassword:
                Log.error('密码不一致')
                return Result.error(BaseEnum.PASSWORD_NOT_EQUAL_ERROR)
            
            user = await UserService.hasUsername(username)
            if user == True:
                Log.error('用户已存在')
                return Result.error(BaseEnum.USER_EXISTED_ERROR)

            # 构造 User
            user = {
                "username": username,
                "password": password,
                "avatar": 'https://varitall.oss-cn-beijing.aliyuncs.com/icon/default-avatar-01.png'
            }
            user = await UserService.createUser(user)
            if user == None:
                Log.error('用户名已存在，创建失败')
                return Result.error(BaseEnum.USER_EXISTED_ERROR)

            Redis.setItem(BaseConstant.REGISTER_USERNAME_KEY % username, {
                "id": user.id
            }, -1)

            return Result.success()
    except Exception as e:
        Log.error('注册异常', e)
        return Result.error(BaseEnum.SERVICE_ERROR)


